package com.chuangyang.fixboxmaster.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.Order;
import com.chuangyang.fixboxmaster.bean.PayType;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.adapter.PayTypeAdapter;
import com.chuangyang.fixboxmaster.ui.fragment.OrderDetailFragment;
import com.chuangyang.fixboxmaster.ui.widgets.ItemView;
import com.chuangyang.fixboxmaster.ui.widgets.MyProgressDlg;
import com.chuangyang.fixboxmaster.utils.pay.Ping.ChargeInfo;
import com.chuangyang.fixboxmaster.utils.pay.Ping.PingUtil;
import com.google.gson.Gson;
import com.pingplusplus.android.PaymentActivity;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2015/4/30.
 */
public class PayActivity extends BaseActivity implements AdapterView.OnItemClickListener,View.OnClickListener  {
    private ListView payTypeListView;
    private PayTypeAdapter mAdapter;
    private TextView mTotalPriceView;
    private ItemView mPayView;
    private Button mPayBtn;
    private LinearLayout mCostDetailView;
    private ArrayList<PayType> mPayTypes = new ArrayList<>();
    private PayType mSelectPayType;
    private Order mOrder;
    private int mTotalPrice;
    public static final int REQUEST_CODE_PING_PAY = 9;

    private Handler mHandler = new Handler();
    private View mHeaderView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        mHeaderView = LayoutInflater.from(this).inflate(R.layout.activity_pay_header, null);
        initView();
        mOrder = (Order)getIntent().getExtras().getSerializable("order");
        if(mOrder==null){
            finish();
        }
        mTotalPrice = (int)(mOrder.totalPrice);
        payTypeListView = (ListView)findViewById(R.id.pay_type_list);
        payTypeListView.addHeaderView(mHeaderView,null,false);
        initPayType();
        mAdapter = new PayTypeAdapter(this,mPayTypes);
        payTypeListView.setAdapter(mAdapter);
        payTypeListView.setOnItemClickListener(this);
        initData();
    }

    private void initView(){
        mCostDetailView = (LinearLayout)mHeaderView.findViewById(R.id.order_cost_ll);
        mCostDetailView.setOnClickListener(this);
        mTotalPriceView = (TextView)mHeaderView.findViewById(R.id.order_cost);
        mPayView = (ItemView)mHeaderView.findViewById(R.id.real_cost);
        mPayBtn = (Button)findViewById(R.id.btn_bottom);
        mPayBtn.setOnClickListener(this);
    }

    private void initData(){
        mTotalPriceView.setText("￥" + mTotalPrice);
        mPayView.setRightItemDescription("￥" + mTotalPrice);
    }

    private void initPayType(){
        PayType zhifubao = new PayType();
        zhifubao.type = PayType.PAY_TYPE_ZHIFUBAO;
        zhifubao.isCheck = true;
        mPayTypes.add(zhifubao);
        mSelectPayType = zhifubao;

        PayType weixin = new PayType();
        weixin.type = PayType.PAY_TYPE_WEIXIN;
        weixin.isCheck = false;
        mPayTypes.add(weixin);

    }

    private void initChecked(ArrayList<PayType> payTypes){
        if (payTypes == null || payTypes.size() <= 0)
            return;
        for (PayType type : payTypes)
        {
            type.isCheck = false;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position >= 1)
        {
            initChecked(mPayTypes);
            PayType type = mPayTypes.get(position - 1);
            type.isCheck = true;
            mAdapter.notifyDataSetChanged();
            mSelectPayType = type;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case  R.id.btn_bottom:
                getPingCharge();
                break;
            case R.id.order_cost_ll:
                Intent costDetailIntent = new Intent(this, ModuleActivity.class);
                costDetailIntent.putExtra(ModuleActivity.TYPE, ModuleActivity.COST_DETAIL_ACTIVITY_02);
                costDetailIntent.putExtra(ModuleActivity.ORDER_ID, ""+mOrder.id);
                startActivity(costDetailIntent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == REQUEST_CODE_PING_PAY)
        {
            if (resultCode == RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                if (result != null)
                {
                    if (result.equals("success"))
                    {
                        dismissLoadingView();
                        showLoadingView();
                        mPayBtn.setClickable(false);
                        mPayBtn.setText("支付结果确认中");
                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingView();
                                showToast("订单支付成功");
                                Intent intent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString("action","pay_success");
                                bundle.putInt("price",(int)mOrder.totalPrice);
                                intent.putExtras(bundle);
                                setResult(OrderDetailFragment.RESULT_CODE_PAY_OK,intent);
                                finish();
                            }
                        };
                        mHandler.postDelayed(runnable,1000);
                    }
                    else if (result.equals("fail"))
                    {
                    }
                    else if (result.equals("cancel"))
                    {
                    }
                    else if (result.equals("invalid"))
                    {
                    }
                }
            } else if (resultCode == RESULT_CANCELED) {
            }
        }
    }


    private void getPingCharge(){
        showLoadingView();
        HashMap<String, String> param = new HashMap<>();
        param.put("order_no", ""+mOrder.orderId);
        param.put("id", ""+ PingUtil.PING_APP_ID);
        String channel = "";
        if (mSelectPayType.type == PayType.PAY_TYPE_ZHIFUBAO)
        {
            channel = PingUtil.PING_CHANNEL_ALIPAY;
        }
        else if (mSelectPayType.type == PayType.PAY_TYPE_WEIXIN)
        {
            channel = PingUtil.PING_CHANNEL_WX;

        }
        else if (mSelectPayType.type == PayType.PAY_TYPE_YINLIAN)
        {
            channel = PingUtil.PING_CHANNEL_UPMP;
        }
        else if (mSelectPayType.type == PayType.PAY_TYPE_ZHIFUBAO_OTHER)
        {
            channel = PingUtil.PING_CHANNEL_ALIPAY_OTHER;

        }
        else if (mSelectPayType.type == PayType.PAY_TYPE_WEIXIN_OTHER)
        {
            channel = PingUtil.PING_CHANNEL_WX_OTHER;
        }
        if (mOrder != null)
        {
            param.put("channel", channel);
            param.put("amount", ""+(int) (mOrder.totalPrice)*100);
            param.put("client_ip", ""+ StringUtils.getDeviceIP(this));
            param.put("currency", "cny");
            param.put("subject", ""+mOrder.orderTitle);
            param.put("appType", "2");
            if (mOrder.orderDes != null)
                param.put("body", ""+mOrder.orderDes);
            if (mSelectPayType.type == PayType.PAY_TYPE_WEIXIN_OTHER)
            {
            }
            else if (mSelectPayType.type == PayType.PAY_TYPE_ZHIFUBAO_OTHER)
            {
            }
            else
            {
                addRequest(new GsonRequest<>(FixBoxApi.PING_CHARGE,param, ChargeInfo.class, chargeResponseListener));
            }
        }
    }

    private Response.Listener<ChargeInfo> chargeResponseListener = new Response.Listener<ChargeInfo>(){
        @Override
        public void onResponse(ChargeInfo response) {
            dismissLoadingView();
            Gson gson = new Gson();
            String charge = gson.toJson(response.result);
            Intent intent = new Intent();
            String packageName = getPackageName();
            ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
            intent.setComponent(componentName);
            intent.putExtra(PaymentActivity.EXTRA_CHARGE, charge);
            startActivityForResult(intent, REQUEST_CODE_PING_PAY);
        }
    };

    private void showToast(final String msg){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(PayActivity.this, msg,Toast.LENGTH_SHORT).show();
            }
        };
        mHandler.post(runnable);
    }

    public MyProgressDlg mProgressDialog;
    /**
     * 显示加载框
     */
    public void showLoadingView() {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {

            public void run() {
                if(mProgressDialog==null){
                    mProgressDialog = new MyProgressDlg(PayActivity.this, R.style.dialog2);
                    mProgressDialog.setCanceledOnTouchOutside(false);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();}
            }
        });
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissLoadingView();
            }
        },8000);
    }

    public void dismissLoadingView() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

}
